<script setup lang="ts">
import signCalendar from "@/components/signCalendar/index.vue"
import {computed, onBeforeMount, ref} from "vue";
import {commonConsoleLog, ECode, iconFontAddress} from "@/util/commonUtil";
import {message} from "ant-design-vue";
import {getCurrentUserCredits, getSignDataByUserUid, retroactive, userSignIn} from "@/api/user/user";
import {dateFormat} from "@/util/timeUtil";
import {userConfigStore} from "@/store/user/userConfigStore";
import {useSystemDictStore} from "@/store/system/systemDictStore";
import _ from "lodash";
import coderCalendar from "@/components/coderCalendar/index.vue"
import {TrophyOutlined, RedoOutlined, createFromIconfontCN} from "@ant-design/icons-vue"
import {useSysEventStore} from "@/store/system/SysEventStore";
import {getCookie} from "@/util/cookieUtil";
import {loginConfigStore} from "@/store/user/loginConfigStore";
import {cookieToken} from "@/config/CookieConfig";
import {recorderBehavior} from "@/api/system/system";

onBeforeMount(() => {
  getSignDate(false)
  // 3S后埋点信息上报
  setTimeout(() => {
    recorderBehavior({'otherData': '签到', 'behavior': 'VISIT_PAGE'}).then((response: any) => {
      if (response.code == ECode.SUCCESS) {
        commonConsoleLog('签到页信息上报成功')
      }
    })
  }, 3000)
})
// 引入阿里图标库
const IconFont = createFromIconfontCN({
  scriptUrl: iconFontAddress,
});
const calendar = ref<any>({
  open: false,
  unClick: true,
  showTop: false,
  maxChoose: 0, //补签卡
  signedDates: []
})
const chooseDatesText = ref<string>('选择补签日期')
const chooseDates = ref<any>([])
const continuousDays = ref<number>(0)
const signInObject = ref<any>({})
const isSignIn = ref<boolean>(false)
const credits = ref<number>(0)
const dateStr = ref<string>('')
const calendarList = ref<any>([])
const userInfo: any = computed(() => userConfigStore().userInfo)
const userLevelImagesDictList: any = computed(() => useSystemDictStore().UserLevelImages)
const showModel = ref<boolean>(false)

function getLvImage(level: any) {
  if (_.isEmpty(userLevelImagesDictList.value)) {
    return;
  }
  return userLevelImagesDictList.value[level - 1].dictValue;
}

function handleChange(date: any) {
  dateStr.value = date
  chooseDates.value = []
  getSignDate(true)
}

function getSignDate(refresh: boolean) {
  chooseDates.value = [];
  chooseDatesText.value = "选择补签日期";
  let params: any = {}
  params.refresh = refresh
  params.dateStr = dateStr.value
  getSignDataByUserUid(params).then((response: any) => {
    if (response.code == ECode.SUCCESS) {
      calendar.value.maxChoose = response.data.retroactiveCard;
      calendar.value.signedDates = response.data.signedDataList;
      isSignIn.value = response.data.todayIsSignIn;
      continuousDays.value = response.data.continuousDays;
      calendarList.value = response.data.calendarList;
    } else {
      message.error(response.message)
    }
  })
}

function chooseHandle(data: any) {
  if (data.length > 0) {
    chooseDates.value = data;
    let str = "";
    data.forEach((v: any) => {
      str = str + dateFormat(v, "d") + "、";
    });
    chooseDatesText.value = `选中${str.substring(0, str.length - 1)}号补签`;
  } else {
    chooseDatesText.value = "选择补签日期";
  }
}

function showCreditsDetail() {
  // 发送个人中心领域事件
  let event = {
    "type": "personCenter",
    "action": "CreditsDetail",
    "time": new Date(),
  }
  useSysEventStore().setDomainEventMessage(event)
}

async function repairSignHandle() {
  if (chooseDates.value.length > 0 && chooseDates.value.length > calendar.value.maxChoose) {
    message.warning("补签次数不足");
    return;
  }
  if (chooseDates.value.length > 0) {
    let params: any = {};
    params.retroactiveDate = chooseDates.value;
    await retroactive(params).then((response: any) => {
      if (response.code == ECode.SUCCESS) {
        message.success("补签成功")
        useSysEventStore().setSignInMessage(Math.random())
        getSignDate(true);
        getUserCredits(true);
      }
    })
  } else {
    message.warning("请先选择补签日期");
  }
}

function getUserCredits(refresh: boolean) {
  if (refresh) {
    let isLogin = getCookie(cookieToken)
    // 判断是否登录
    if (!isLogin) {
      isSignIn.value = false
      // 未登录，自动弹出登录框
      loginConfigStore().setLoginMessage(Math.random())
      return;
    }
  }
  let params: any = {}
  params.refresh = refresh
  getCurrentUserCredits(params).then((response: any) => {
    if (response.code == ECode.SUCCESS) {
      credits.value = response.data
    }
  })
}

function refresh() {
  getSignDate(true)
  getUserCredits(true)
}

async function clickSignIn() {
  let isLogin = getCookie(cookieToken)
  // 判断是否登录
  if (!isLogin) {
    isSignIn.value = false
    // 未登录，自动弹出登录框
    loginConfigStore().setLoginMessage(Math.random())
    return;
  }
  await userSignIn().then((response: any) => {
    if (response.code == ECode.SUCCESS) {
      isSignIn.value = true;
      signInObject.value = response.data
      useSysEventStore().setSignInMessage(Math.random())
      getSignDate(true);
      getUserCredits(true)
      showModel.value = true
    } else {
      message.error(response.message)
    }
  })
}
function clickModel(){
  showModel.value = false
}
</script>

<template>
  <section class="repair-sign-dialog max-w-screen-lg m-auto mt-8 w-full">
    <a-row :gutter="[16,16]" class="justify-between">
      <a-col :span="7" style="border: var(--border)" class="rounded">
        <div class="userInfo">
          <div class="flex flex-col items-center mt-4 pl-5 pr-5">
            <div class="relative">
              <a-avatar v-if="userInfo.photoUrl" :src="userInfo.photoUrl" size="large" class="h-10 w-10"
                        style="border: var(--vip-border)"/>
              <a-avatar v-else size="large" class="h-10 w-10 flex items-center justify-center"
                        style="border: var(--vip-border)">
                {{ String(userInfo.nickName).slice(0, 1) }}
              </a-avatar>
              <sub class="badgeSup h-4 w-4 absolute -bottom-1 -right-1" v-if="userInfo.userTag > 0">
                <img src="@/assets/vip/vip.svg" class="h-full w-full" alt="vipBadge">
              </sub>
            </div>
          </div>
          <div class="w-full flex justify-center items-center mt-4">
          <span class="text-base overflow-hidden font-semibold line-clamp-1"
                :class="userInfo.userTag>0?'text-rose-500':''">
            {{ userInfo.nickName }}
          </span>
            <span class="userLevel h-5 w-auto ml-2" v-if="userInfo.userLevel">
            <img class="w-full h-full" :src="getLvImage(userInfo.userLevel)" alt="userLevel">
          </span>
          </div>
        </div>
        <coderCalendar/>
      </a-col>
      <a-col :span="16" style="border: var(--border)" class="rounded flex flex-col h-full">
        <div class="flex items-center justify-center">
          <signCalendar
              class="flex h-full"
              @handlePrev="handleChange"
              @handleNext="handleChange"
              :showOpenBtn="false"
              :signedDates="calendar.signedDates"
              :maxChoose="calendar.maxChoose"
              :chooseCallBack="chooseHandle"
              :chooseDates="chooseDates"
              :calendarList="calendarList"/>
        </div>
        <div class="calendarBottom ml-12 mb-8 flex justify-between items-center">
          <div class="calendarBottomLeft">
              <span v-if="chooseDates.length > 0">{{ chooseDatesText }}</span>
              <a-tooltip v-if="chooseDates.length > 0">
                <template #title>
                  补签选中日期
                </template>
                <a-button @click="repairSignHandle" type="primary" class="ml-4">补签</a-button>
              </a-tooltip>
              <span v-if="chooseDates.length == 0">
              <a-tooltip>
                <template #title>
                  通过完成签到、任务、发布文章、问答、评论、动态可获取积分，积分可用于参与抽奖和资源兑换
                </template>
                <TrophyOutlined/>
              </a-tooltip>
              <span class="font-semibold text-rose-500 ml-2 cursor-pointer" @click="showCreditsDetail"> {{
                  credits
                }}</span>
              积分
              <a-tooltip>
                <template #title>
                  每隔10分钟自动刷新
                </template>
                <RedoOutlined @click="refresh" class="hover:text-blue-500"/>
              </a-tooltip>
            </span>
          </div>
          <div class="calendarBottomRight flex items-center gap-4">
            <span v-if="chooseDates.length == 0">
            <a-button v-if="!isSignIn" type="primary" round @click="clickSignIn">立即签到</a-button>
            </span>
            <div v-if="chooseDates.length == 0 && isSignIn">
              <IconFont type="icon-qiandao" class="text-base"/>
              你已经连续签到
              <span class="font-semibold text-rose-500">{{ continuousDays }} </span>天啦！
            </div>
          </div>
        </div>
      </a-col>
    </a-row>
    <a-modal v-model:open="showModel" @cancel="clickModel">
      <template #title>
        <span class="w-full flex justify-center text-center">签到结果</span>
      </template>
      <div class="flex w-full justify-center items-center mt-8 cursor-pointer">
        <div class="signCalendarResult flex w-28 h-28 flex-col justify-center items-center">
          <span>签到成功</span>
        </div>
      </div>
      <template #footer>
        <div class="hidden"></div>
      </template>
    </a-modal>
  </section>
</template>

<style scoped lang="less">
.signCalendarResult{
  border-radius: 50%;
  background-image: linear-gradient(#2dabff,#1b83ff);
  color: #fff;
}
</style>
